package com.zhj.algorithm.search.str;

public class RKSearch implements StrSearch {

    @Override
    public int search(String A, String B) {
        if (A == null || A.length() == 0 || B == null || B.length() == 0) {
            return -1;
        }
        for (int i = 0; i < A.length(); i++) {
            if (i + B.length() > A.length()) {
                break;
            }
            String ASub = A.substring(i, i + B.length());
            if (hash(B) == hash(ASub) && compareString(i, A, B)) {
                return i + 1;
            }
        }
        return -1;
    }

    private int hash(String str) {
        int hashcode = 0;
        for (int i = 0; i < str.length(); i++) {
            hashcode += str.charAt(i) - 'a';
        }
        return hashcode;
    }

    private boolean compareString(int i, String A, String B) {
        boolean flag = true;
        for (int j = 0; j < B.length(); j++) {
            if (B.charAt(j) != A.charAt(i + j)) {
                flag = false;
                break;
            }
        }
        return flag;
    }
}
